package com.meitutest.autoscript.T9;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiSelector;

import com.meitutest.autoscript.fluency.SwipeDevice;
import com.meitutest.autoscript.utils.TestReport;
import com.meitutest.autoscript.utils.WifiUtils;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by CrystalChen on 2018/4/2.
 */

public class T9 {
    UiDevice uiDevice;
    Context context;
    private int h;
    private int w;

    private int h_x1;
    private int h_y1;
    private int h_x2;
    private int h_y2;

    private int v_x1;
    private int v_y1;
    private int v_x2;
    private int v_y2;

    T9() {
        this.uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        T9Watcher watcher = new T9Watcher(uiDevice);
        uiDevice.registerWatcher("t9_watcher", watcher);
        this.h = uiDevice.getDisplayHeight();
        this.w = uiDevice.getDisplayWidth();

        this.h_x1 = (int) (w * 0.2);
        this.h_y1 = (int) (h * 0.5);
        this.h_x2 = (int) (w * 0.8);
        this.h_y2 = (int) (h * 0.5);

        this.v_x1 = (int) (w * 0.5);
        this.v_y1 = (int) (h * 0.2);
        this.v_x2 = (int) (w * 0.5);
        this.v_y2 = (int) (h * 0.8);
        this.context = InstrumentationRegistry.getContext();
    }

    public void exit() throws InterruptedException {
        uiDevice.pressBack();
        uiDevice.pressBack();
        uiDevice.pressBack();
        uiDevice.pressHome();
        uiDevice.pressHome();
        Thread.sleep(1000);
    }

    public void goSettings(String moduleName) throws Exception {
        exit();
        swipeFromRight(30);
        uiDevice.findObject(By.text(Pattern.compile("设置|Settings"))).click();
        Thread.sleep(1000);

        if (uiDevice.hasObject(By.text(Pattern.compile("同意|Agree")))) {
            uiDevice.findObject(By.text(Pattern.compile("同意|Agree"))).click();
        }
        Thread.sleep(1000);
        while (!uiDevice.hasObject(By.text(Pattern.compile(moduleName)))) {
            swipeFromBottom(30);
            Thread.sleep(500);
        }
        uiDevice.findObject(By.text(Pattern.compile(moduleName))).click();
    }

    private void goDeveloper() throws Exception {
        exit();
        uiDevice.findObject(By.text(Pattern.compile("拨号|Dialer"))).click();
        Thread.sleep(1000);
        if (uiDevice.hasObject(By.text(Pattern.compile("同意|Agree")))) {
            uiDevice.findObject(By.text(Pattern.compile("同意|Agree"))).click();
        }
        Thread.sleep(1000);
        uiDevice.findObject(By.text("*")).click();
        uiDevice.findObject(By.text("#")).click();
        uiDevice.findObject(By.text("6")).click();
        uiDevice.findObject(By.text("3")).click();
        uiDevice.findObject(By.text("4")).click();
        uiDevice.findObject(By.text("8")).click();
        uiDevice.findObject(By.text("8")).click();
        uiDevice.findObject(By.text("#")).click();
        Thread.sleep(1000);
        uiDevice.findObject(By.text("开发者选项")).click();
        Thread.sleep(1000);
    }

    public void screenAlwaysOn() throws Exception {
        goDeveloper();
        Thread.sleep(1000);
        if (uiDevice.hasObject(By.text(Pattern.compile("同意|OK|确定|Agree|允许|Allow")))) {
            uiDevice.findObject(By.text(Pattern.compile("同意|OK|确定|Agree|允许|Allow"))).click();
        }
        if (uiDevice.hasObject(By.res("com.android.settings:id/text2_ofnote"))) {
            TestReport.i("T9_screenAlwaysOn: 发现美图帐号登录屏");
            uiDevice.pressBack();
        }
        UiObject s1 = uiDevice.findObject(new UiSelector().resourceId("com.android.settings:id/switch_widget"));
        while (s1.exists() && !s1.isChecked()) {
            uiDevice.findObject(By.res("com.android.settings:id/switch_widget")).click();
            TestReport.i("T9_screenAlwaysOn: 开启开发者选项");
        }
        UiObject swicher = uiDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").instance(0));
        if (!swicher.isChecked()) {
            swicher.click();
        }
    }

    public void connectWifi() throws Exception {
        WifiUtils.adaptWifiConditon();
        Thread.sleep(1000);
        UiObject ui = uiDevice.findObject(new UiSelector().textMatches("允许|Allow"));
        if (ui.exists()) {
            ui.click();
        }
    }

    public void openBlueTeeth() throws Exception {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
        Thread.sleep(1000);
        UiObject ui = uiDevice.findObject(new UiSelector().textMatches("允许|Allow"));
        if (ui.exists()) {
            ui.click();
        }
    }

    public void openGPS() throws IOException {
        uiDevice.executeShellCommand("settings put secure location_providers_allowed +gps");
    }

    public void nonScreenLock() throws Exception {
        goSettings("指纹与密码|Fingerprint and Password");
        Thread.sleep(1000);
        swipeFromBottom(30);
        uiDevice.findObject(new UiSelector().textMatches("锁屏密码|Lock Screen Password")).click();
        Thread.sleep(1000);
        UiObject swicher = uiDevice.findObject(new UiSelector().resourceId("android:id/switch_widget"));
        if (!swicher.isChecked()) {
            swicher.click();
        }

    }

    public void set24Mode() throws Exception {
        goSettings("通用|General");
        Thread.sleep(1000);
        uiDevice.findObject(new UiSelector().textMatches("日期和时间|Date & time")).click();
        Thread.sleep(1000);
        UiObject swicher = uiDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").instance(1));
        if (!swicher.isChecked()) {
            swicher.click();
        }

    }

    public void openBrowser() throws Exception {
        exit();
        uiDevice.findObject(new UiSelector().textMatches("浏览器|Browser")).click();
        Thread.sleep(1000);
        UiObject ok = uiDevice.findObject(new UiSelector().textMatches("同意|Agree|Accept"));
        if (ok.exists()) {
            ok.click();
        }
    }

    public void swichAospByCmd() throws Exception {
        String Android_KEY = "com.android.inputmethod.latin/.LatinIME";
        String cmd = "settings put secure default_input_method " + Android_KEY;
        uiDevice.executeShellCommand(cmd);
        TestReport.i("切换到输入法[Android]");
    }

    public void swichAosp() {
        try {
            goSettings("通用|General");
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("语言和输入法|Languages & input")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("虚拟键盘|Virtual keyboard")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("管理键盘|Manage keyboards")).click();
            Thread.sleep(1000);
            UiObject swicher1 = uiDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").instance(1));
            if (swicher1.isChecked()) {
                swicher1.click();
            }
            UiObject swicher2 = uiDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").instance(0));
            if (!swicher2.isChecked()) {
                swicher2.click();
            }

        } catch (Exception e) {
            e.printStackTrace();
            TestReport.e("T9_swichAosp: " + e.getMessage());
        }
    }

    public void recoveryAll() {
        try {
            goSettings("通用|General");
            Thread.sleep(1000);
            swipeFromBottom(30);
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("清除数据|Erase data")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("恢复出厂设置|Reset the phone")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("格式化手机存储|Formatting cell phone storage")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("开始恢复|Start to reset")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("确定|OK")).click();
            Thread.sleep(1000);

        } catch (Exception e) {
            e.printStackTrace();
            TestReport.e("T9_recoveryAll: " + e.getMessage());
        }
    }

    public void swichEng() {
        try {
            goSettings("通用|General");
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("语言和输入法|Languages & input")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("语言|Languages")).click();
            Thread.sleep(1000);
            uiDevice.findObject(new UiSelector().textMatches("English")).click();
            Thread.sleep(1000);

        } catch (Exception e) {
            e.printStackTrace();
            TestReport.e("T9_swichEng: " + e.getMessage());
        }
    }

    public void wakeupScreen() throws RemoteException {
        if (!uiDevice.isScreenOn()) {
            uiDevice.pressKeyCode(26);
        }
        if (uiDevice.hasObject(By.res("com.android.systemui:id/meitu_hour_second"))) {
            SwipeDevice swipeDevice = new SwipeDevice(uiDevice);
            swipeDevice.fromBottom(1, 50);
        }
    }

    public void swipeFromTop(int step) {
        uiDevice.swipe(v_x1, v_y1, v_x2, v_y2, step);
    }

    public void swipeFromBottom(int step) {
        uiDevice.swipe(v_x2, v_y2, v_x1, v_y1, step);
    }

    public void swipeFromRight(int step) {
        uiDevice.swipe(h_x2, h_y2, h_x1, h_y1, step);
    }

    public void swipeFromLeft(int step) {
        uiDevice.swipe(h_x1, h_y1, h_x2, h_y2, step);
    }

    /**
     * 通过startActivity的方式启动应用
     */
    public void clickAppIcon(String appName) throws Exception {
        uiDevice.pressBack();
        uiDevice.pressBack();
        uiDevice.pressBack();
        uiDevice.pressBack();
        uiDevice.pressHome();
        uiDevice.pressHome();
        uiDevice.pressHome();
        uiDevice.pressHome();
        while (true) {
            UiObject icon = uiDevice.findObject(new UiSelector().text(appName));
            if (icon.exists()) {
                icon.click();
                if (uiDevice.hasObject(By.text(Pattern.compile("同意|允许|确认|知道了")))) {
                    uiDevice.findObject(By.text(Pattern.compile("同意|允许|确认|知道了"))).click();
                }

                return;
            } else {
                //如果当前桌面不存在icon，则尝试查找文件夹
                List<UiObject2> dirs = uiDevice.findObjects(By.descContains("文件夹"));
                if (dirs != null && dirs.size() > 0) {
                    for (UiObject2 dirsInstance : dirs) {
                        dirsInstance.click();
                        Thread.sleep(1000);
                        icon = uiDevice.findObject(new UiSelector().text(appName));
                        if (icon.exists()) {
                            icon.click();
                            return;
                        } else {
                            uiDevice.pressBack();
                        }
                    }
                }
                Thread.sleep(1000);
                //如果文件夹仍然没有，则向右滑动
                swipeFromRight(50);
                Thread.sleep(1000);
            }

        }

    }
}
